package com.ujs.code.removeElement;

import java.util.Arrays;

/**
 * @author zhangshihao
 * @create 2023-09-12 9:57
 * <p>
 * 26. 删除有序数组中的重复项
 */
public class RemoveDuplicates {
    public static void main(String[] args) {
        RemoveDuplicates removeDuplicates = new RemoveDuplicates();
        int[] nums = {1, 2, 2, 2, 3, 3};
        int i = removeDuplicates.removeDuplicates2(nums);
        System.out.println(i);
    }

    public int removeDuplicates(int[] nums) {
        if (nums.length == 1) {
            return 1;
        }
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                int j = 0; // 元素相同的个数
                while (nums[i] == nums[i + j]) {
                    j++;
                    if (i + j >= nums.length) {
                        return i + 1;
                    }
                }
                for (int k = 1; k < j; k++) {
                    nums[i + k] = nums[i + j];
                }
            }

        }
        return nums.length;
    }

    public int removeDuplicates2(int[] nums) {
        int n = nums.length;
        if (n == 0) return 0;
        int fast = 1, slow = 1;
        while (fast < n) {
            if (nums[fast] != nums[fast - 1]) {
                nums[slow] = nums[fast];
                ++slow;
            }
            ++fast;
        }
        return slow;
    }
}
